package com.zoe.onelink.plugin.check;

import com.zoe.onelink.plugin.check.model.PropertyCheckResult;
import com.zoe.onelink.util.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>标题: </p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2022</p>
 * <p>公司: 智业软件股份有限公司</p>
 *
 * @version: 1.0
 * @author: ruansheng
 * @date: 2022-09-19
 */
@Slf4j
public abstract class AbstractEnvironmentChecker implements EnvironmentChecker {

    private final ApplicationContext applicationContext;

    public AbstractEnvironmentChecker() {
        this(SpringUtil.getApplicationContext());
    }

    public AbstractEnvironmentChecker(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    protected ApplicationContext getApplicationContext() {
        return this.applicationContext;
    }

    protected Environment getEnvironment() {
        return this.applicationContext.getEnvironment();
    }

    protected <T> T getBean(Class<T> targetType) {
        return this.getApplicationContext().getBeanProvider(targetType).getIfAvailable();
    }

    protected <T> List<T> getBeanList(Class<T> targetType) {
        return this.getApplicationContext().getBeanProvider(targetType).stream()
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
    }

    protected String getProperty(String key) {
        return this.getEnvironment().getProperty(key);
    }

    protected <T> T getProperty(String key, Class<T> targetType) {
        return this.getEnvironment().getProperty(key, targetType);
    }

    protected <T> T getProperty(String key, Class<T> targetType, T defaultValue) {
        return this.getEnvironment().getProperty(key, targetType, defaultValue);
    }

    @Override
    public List<PropertyCheckResult<?>> check() {
        return this.doCheck();
    }

    protected abstract List<PropertyCheckResult<?>> doCheck();

}
